package edu.dayu.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Set;

@Component
public class CurrentLimitUtil {

    private static final Integer SECOND = 1000;


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public boolean current(String name,Integer count,Integer limitTime){
        long time = System.currentTimeMillis();
        limitTime = limitTime*SECOND;
        Set<Object> keys = redisTemplate.opsForHash().keys(name);
        boolean flag;
        if (keys.size()<count){
            redisTemplate.opsForHash().put(name,keys.size()+"",time);
            flag = true;
        }
        else {
            Long date = (Long) redisTemplate.opsForHash().get(name, 0+"");
            if (time-date>limitTime){
                keys.forEach(item->{
                    Integer i = Integer.parseInt(item.toString());
                    if (i>0){
                        redisTemplate.opsForHash().put(name,i-1+"",redisTemplate.opsForHash().get(name, i+""));
                    }
                });
                redisTemplate.opsForHash().put(name,count-1+"",time);
                flag = true;
            }else {
                flag = false;
            }
        }
        return flag;
    }

}
